﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;

namespace LOC
{
    /// <summary>
    /// Contains static methods for counting lines in files and directories
    /// </summary>
    public static class LineCounter
    {
        /// <summary>
        /// Counts number of lines in all files that match any of given masks in directory and its subdirectories
        /// </summary>
        /// <param name="path">Path to directory</param>
        /// <param name="masks">Search patterns array. Only '*' and '?' are supported. Pass null to count all files</param>
        /// <returns></returns>
        public static List<CountResult> CountDir(string path, params string[] masks)
        {
            if (masks == null || masks.Length == 0)
                return CountDir(path);
            IEnumerable<CountResult> result = new List<CountResult>();
            foreach (string mask in masks)
                result = result.Concat(CountDir(path, mask));
            return result.ToList();
        }

        /// <summary>
        /// Counts number of lines in all files that match given mask in directory and its subdirectories
        /// </summary>
        /// <param name="path">Path to directory</param>
        /// <param name="mask">Search pattern. Only '*' and '?' are supported. Pass null to count all files</param>
        /// <returns>List of CountResult for all files that matched mask</returns>
        public static List<CountResult> CountDir(string path, string mask = null)
        {
            var result = new List<CountResult>();
            string[] files = (mask != null) ?
                Directory.GetFiles(path, mask) :
                Directory.GetFiles(path);
            foreach (string file in files)
                result.Add(new CountResult()
                {
                    FileName = Path.GetFileName(file),
                    LinesCount = CountFile(file)
                });
            string[] dirs = Directory.GetDirectories(path);
            foreach (string dir in dirs)
                result = result.Concat(CountDir(dir, mask)).ToList();
            return result;
        }

        /// <summary>
        /// Counts number of lines in text file
        /// </summary>
        /// <param name="path">Path to file</param>
        /// <returns>Number of lines</returns>
        public static int CountFile(string path)
        {
            return File.ReadAllLines(path).Length;
        }

    }
}
